﻿using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace Skynet.CommonLibrary.Extension.XML
{
    /// <summary>
    /// 通过XSD文件验证XML
    /// </summary>
    ///<remarks>
    /// 作者：         李志强
    /// 开发时间：  2011-04-11
    /// </remarks>
   public  class XMLValidation
    {
       StringBuilder _errString = new StringBuilder();
        public bool  CheckXmlValidate(string xml,string xsdFilePath)
        {
            _errString= new StringBuilder();
            XmlReader xmlRead = null;
            try
            {
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                StringReader sRead = new StringReader(xml);
                schemaSet.Add(null, xsdFilePath);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationEventHandler += this.ValidationEventCallBack;
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas = schemaSet;
                xmlRead = XmlReader.Create(sRead, settings);
                while (xmlRead.Read())
                {
                }
                if (_errString.ToString() == String.Empty)
                {
                    return true;
                }
                else
                {
                    //Log.WriteLog("验证失败！原因可能是：" + ErrString);
                    return false;
                }
            }
            catch (XmlException exec)
            {
                //Log.WriteLog(exec.Message);
                _errString.Append(exec.Message);
                return false;
            }
            finally
            {
                if (xmlRead != null)
                {
                    xmlRead.Close();
                }
            }
        }

        private void ValidationEventCallBack(Object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)//区分是警告还是错误 
            {
                //Log.WriteLog("验证成功!警告：" + e.Message);
            }
            else
            {
                _errString.Append(e.Message + Environment.NewLine);
            }
        }

        public string ErrorMsg
        {
            get 
            {
                return _errString.ToString();
            }
        }
    }
}
